/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package portal.system.inzerat;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Riso-Desktop
 */
@WebServlet(name = "VyhladavanieInzeratov", urlPatterns = {"/vyhladaj"})
public class VyhladavanieInzeratov extends HttpServlet {

    String driver = portal.constants.Database.DATABASE_DRIVER;
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    String userName = portal.constants.Database.DATABASE_USER;
    String password = portal.constants.Database.DATABASE_PASSWORD;
    String URL = portal.constants.Database.DATABASE_URL;
    HttpSession session;
    PrintWriter out;
    String query;
    @Override
    public void init() {
        try {
            super.init();
            Class.forName(driver);
            con = DriverManager.getConnection(URL, userName, password);
        } catch (Exception ex) {
        }
    }

    public synchronized int VypisInzeraty(HttpServletRequest request, HttpServletResponse response) {
        String podkategoria = request.getParameter("podkategoria");
        String kategoria = request.getParameter("kategoria");
        int pocet = 0;
        try {
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
            out.println("<meta http-equiv=\"Content-Script-Type\" content=\"text/javascript\">");
            out.println("<title>Vypis Inzeratov</title>");


            out.println("<style>");
            out.println(".inzerat{"
                    + "position: relative;"
                    + "width: 100%;"
                    + "border: 1px solid #ccc;"
                    + "background: #ddd;"
                    + "-moz-border-radius: 4px;"
                    + " border-radius: 4px;"
                    + " color: rgba(0,0,0, .8);"
                    + "text-shadow: 0 1px 0 #fff;"
                    + "line-height: 1.5;"
                    + "}");
            out.println(".inzerat:hover{\n"
                    + "                -webkit-box-shadow: 0px 0px 4px #d6ecec;\n"
                    + "                -moz-box-shadow: 0px 0px 4px #d6ecec;\n"
                    + "                -o-box-shadow: 0px 0px 4px #d6ecec;\n"
                    + "                background: #d6ecec;\n"
                    + "            }");
            out.println(".inzerat:before, .inzerat:after "
                    + "{"
                    + "z-index: -1; "
                    + "position: absolute; "
                    + "content: \"\";"
                    + "bottom: 15px;"
                    + "left: 10px;"
                    + "width: 50%; "
                    + "top: 80%;"
                    + "max-width:300px;"
                    + "background: rgba(0, 0, 0, 0.7); "
                    + "-webkit-box-shadow: 0 15px 10px rgba(0,0,0, 0.7);"
                    + "-moz-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7);"
                    + "box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7);"
                    + "-webkit-transform: rotate(-3deg);  "
                    + "-moz-transform: rotate(-3deg);  "
                    + "-o-transform: rotate(-3deg);"
                    + "-ms-transform: rotate(-3deg);"
                    + "transform: rotate(-3deg);}"
                    + ".inzerat:after "
                    + "{"
                    + "-webkit-transform: rotate(3deg);"
                    + "-moz-transform: rotate(3deg);"
                    + "-o-transform: rotate(3deg);"
                    + "-ms-transform: rotate(3deg);"
                    + "transform: rotate(3deg);"
                    + "right: 10px;"
                    + "left: auto;"
                    + "}");
            out.println("a:link {color: #333;text-decoration: none;}     \n"
                    + "a:visited {color: #333;text-decoration: none;}  \n"
                    + "a:hover {color: #000000;text-decoration: none;}  \n"
                    + "a:active {color:#000000;text-decoration: none;}");
            out.println(".stranka {"
                    + "font-family: Georgia, \"Times New Roman\", Times, serif;"
                    + "font-style: italic;"
                    + "font-size: 20px;"
                    + "}");
            out.println(".stranky{"
                    + "font-family: Georgia,\"Times New Roman\", Times, serif;"
                    + "}");
            out.println(".obrazok{\n"
                    + "-moz-box-shadow: 2px 2px 1px #888;\n"
                    + "-webkit-box-shadow: 1px 2px 1px #888;\n"
                    + "box-shadow: 2px 2px 1px #888;"
                    + "border:#ccc;\n"
                    + "border-radius: 2px;\n"
                    + "border-style: solid;\n"
                    + "border-width: 1px;"
                    + "border-color: #666666;"
                    + "}");
            out.println("</style>");
            out.println("</head>");
            out.println("<body onLoad=\"window.parent.scroll(0,0);\">");
            //out.println("<body style=\"background-image: url(img/back.png)\">");
            stmt = con.createStatement();
            String sql;
            String limit;
            if (request.getParameter("strana") != null) {
                int strana = Integer.parseInt(request.getParameter("strana"));
                int pocetpol;
                if (session.getAttribute("pocet_poloziek") != null) {
                    pocetpol = (Integer) session.getAttribute("pocet_poloziek");
                } //pocet poloziek na stranu pre neregistrovaných
                else {
                    pocetpol = 10;
                }
                limit = (strana * pocetpol) - pocetpol + ", " + pocetpol;
            } else {
                int pocetpol;
                if (session.getAttribute("pocet_poloziek") != null) {
                    pocetpol = (Integer) session.getAttribute("pocet_poloziek");
                } //pocet poloziek na stranu pre neregistrovaných
                else {
                    pocetpol = 10;
                }
                limit = "0," + pocetpol;
            }
            if (request.getParameter("name_hladaj") != null) {
                query = request.getParameter("name_hladaj");
                query = query.toLowerCase();
                String pom = query;
                ArrayList slova = new ArrayList();
                while (pom.length() > 0) {
                    if (pom.indexOf(" ") > 0) {
                        slova.add(pom.substring(0, pom.indexOf(" ")));
                        pom = pom.substring(pom.indexOf(" ") + 1);
                    } else {
                        slova.add(pom);
                        pom = "";
                    }
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < slova.size(); i++) {
                    sb.append(" +" + slova.get(i));
                }
                sb.append("*");
                query = sb.toString();
                sql = "Select * from inzerat join mesto on inzerat.id_mesta = mesto.id_mesta where Match(inzerat.nazov_inzeratu,inzerat.text_inzeratu) against('"+query+
                "' in boolean mode) AND viditelny = 1 order by datum_pridania desc limit " + limit;
            }else{
                return -1;
            }
            System.out.println(sql);
            vypisStranky(request);
            rs = stmt.executeQuery(sql);
            rs.last();
            int in = rs.getRow();
            rs.beforeFirst();
            while (rs.next()) {
                Inzerat i = new Inzerat();
                i.setCena(rs.getInt("cena"));
                i.setDatum_pridania(rs.getTimestamp("datum_pridania"));
                i.setEmail(rs.getString("email"));
                i.setHeslo(rs.getString("heslo"));
                i.setId_inzeratu(rs.getInt("id_inzeratu"));
                i.setId_usera(rs.getInt("id_usera"));
                i.setMeno(rs.getString("meno"));
                i.setNazov_inzeratu(rs.getString("nazov_inzeratu"));
                i.setText_inzeratu(rs.getString("text_inzeratu"));
                i.setPocet_zobrazeni(rs.getInt("pocet_zobrazeni"));
                i.setId_mesta(rs.getInt("id_mesta"));
                i.setMesto(rs.getString("nazov_mesta"));
                i.setPsc(rs.getString("psc"));
                VypisInzerat(i, response);
                pocet++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (pocet * 205 < 2050) {
            return 2050 + 100;
        } else {
            return pocet * 205 + 100;
        }
    }

    private synchronized void VypisInzerat(Inzerat inzerat, HttpServletResponse response) {
        try {
            SimpleDateFormat s = new SimpleDateFormat("dd.MM.YYYY");
            //TODO: pridať možnosť ponuka/dopyt
            out.println("<div class=inzerat>");
            //out.println("<img src= \"img/oddelovac_hore.png\" />");
            out.println("<table width=\"590\" border=\"0\">");
            out.println("<tr>");
            out.println("<td colspan=\"2\"><a href=./inzerat?c=" + inzerat.getId_inzeratu() + " target=\"iframe_hlavny\">" + inzerat.getNazov_inzeratu() + "</a>  - " + s.format(inzerat.getDatum_pridania()) + "</td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td rowspan=\"3\" width=\"100\" >" + "<a href=./inzerat?c=" + inzerat.getId_inzeratu() + " target=\"iframe_hlavny\">" + "<img class=\"obrazok\" src=\"./displayImage?id=" + inzerat.getId_inzeratu() + "\" height=\"100\"/></a>" + "</td>");
            if (inzerat.getText_inzeratu().length() > 150) {
                out.println("<td rowspan=\"2\">" + inzerat.getText_inzeratu().substring(0, 150) + "..." + "</td>");
            } else {
                out.println("<td rowspan=\"2\">" + inzerat.getText_inzeratu() + "</td>");
            }
            out.println("</tr>");
            out.println("<tr>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Cena: " + inzerat.getCena() + " €" + "<br/>");
            out.println("" + inzerat.getMesto() + "\n" + inzerat.getPsc() + "</td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Zobrazenia: " + inzerat.getPocet_zobrazeni() + "</td>");
            out.println("<td>moznosti inzeratu</td>");
            out.println("</tr>");
            out.println("</table>");
            out.println("</div>");
            //out.println("<img src= \"img/oddelovac_dole.png\" />");
            out.println("<br/>");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        out = response.getWriter();
        session = request.getSession();
        try {
            /* TODO ak hladany vyraz nieje v DB doplniť do hladane_vyrazy a vypísať hladané inzeráty */
            String co = request.getParameter("name_hladaj");
            String sql = "select hladany_vyraz from hladane_vyrazy where hladany_vyraz like '" + co + "'";
            System.out.println(sql);
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            rs.last();
            if (rs.getRow() < 1) {
                sql = "insert into hladane_vyrazy(hladany_vyraz) values('" + co + "')";
                stmt.executeUpdate(sql);
            }
            VypisInzeraty(request, response);
            vypisStranky(request);
            out.println("<br/><br/>");
            out.println("</body>");
            out.println("</html>");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    private void vypisStranky(HttpServletRequest request) {
        String sql;

        sql = "Select count(inzerat.id_inzeratu) as pocet from inzerat join mesto on inzerat.id_mesta = mesto.id_mesta where Match(inzerat.nazov_inzeratu,inzerat.text_inzeratu) against('"+query+
                "' in boolean mode) AND viditelny = 1";

        try {
            ResultSet result;
            stmt = con.createStatement();
            result = stmt.executeQuery(sql);
            result.next();
            int pocetinzeratov = result.getInt("pocet");
            int pocet_poloziek;
            //System.out.println(session.getAttribute("id_usera") + ":" + "pocet_poloziek: " + session.getAttribute("pocet_poloziek"));
            if (session.getAttribute("pocet_poloziek") != null) {
                pocet_poloziek = (Integer) session.getAttribute("pocet_poloziek");
            } //pocet poloziek na stranu pre neregistrovaných
            else {
                pocet_poloziek = 10;
            }
            int pocetstranok = pocetinzeratov / pocet_poloziek;
            out.println("<div align=\"center\" class=\"stranky\" >");
            if (pocetinzeratov % pocet_poloziek > 0) {
                pocetstranok++;
            }
            for (int i = 1; i <= pocetstranok; i++) {
                String values = "";
                if (request.getParameter("name_hladaj") != null) {
                    values = "&name_hladaj=" + request.getParameter("name_hladaj");
                }
                StringBuilder sb = new StringBuilder();
                sb.append("<a href = \"./vyhladaj?strana=" + i + values + "\" target=\"iframe_hlavny\" ");
                if (request.getParameter("strana") != null) {
                    if (Integer.parseInt(request.getParameter("strana")) == i) {
                        sb.append("class=\"stranka\"  >" + i + "</a>");
                    } else {
                        sb.append(" >" + i + "</a>");
                    }
                } else {
                    if (i == 1) {
                        sb.append("class=\"stranka\" >" + i + "</a>");
                    } else {
                        sb.append(">" + i + "</a>");
                    }
                }
                out.println(sb.toString());

            }

            out.println("</div>");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
